<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\FrontendUser;
use App\Models\UserAddress;

class UserAddressController extends Controller
{
    /** 查询用户地址信息 */
    public function getUserAddress()
    {
        $address = $this->getMyAddressOrNew();

        return [
            'id' => $address->id,
            'name' => $address->name,
            'mobile' => $address->mobile,
            'address' => $address->address,
        ];
    }

    /** 保存用户地址信息 */
    public function saveUserAddress()
    {
        request()->validate([
            'name' => 'required',
            'mobile' => 'required',
            'address' => 'required',
        ]);
        $address = $this->getMyAddressOrNew();
        $address->name = request()->name;
        $address->mobile = request()->mobile;
        $address->address = request()->address;
        $address->save();
    }

    private function getMyAddressOrNew()
    {
        /** @var FrontendUser $user */
        $user = auth()->user();

        $address = UserAddress::query()->where('user_id', $user->id)->first();
        if (!$address) {
            $address = new UserAddress();
            $address->user_id = $user->id;
        }

        return $address;
    }
}
